from sqlalchemy import Column, String, Integer, Table, ForeignKey
from sqlalchemy.orm import relationship

from app.models import BaseModel, Base

# 用户-角色关联表（多对多关系）
user_role = Table(
    'user_role',
    Base.metadata,
    Column('user_id', Integer, ForeignKey('users.id'), primary_key=True),
    Column('role_id', Integer, ForeignKey('roles.id'), primary_key=True)
)

# 导入 role_permission 表需要在这里导入避免循环引用
from app.models.permission import role_permission

class Role(BaseModel):
    """角色模型"""
    __tablename__ = "roles"
    
    name = Column(String(50), unique=True, nullable=False, comment="角色名称")
    description = Column(String(200), nullable=True, comment="角色描述")
    code = Column(String(50), unique=True, nullable=False, comment="角色编码")
    
    # 与User模型建立多对多关系
    users = relationship("User", secondary=user_role, back_populates="roles")
    
    # 与Permission模型建立多对多关系
    permissions = relationship("Permission", secondary=role_permission, back_populates="roles")
